<template>
  <el-card>
    <!-- 单据编号放在右上角 -->
    <template #header>
      <div class="card-header">
        <h1 class="title-center">采购单（审核模式）</h1>
        <span class="document-number">单据编号：<u>{{ form.yclcg_code }}</u></span>
      </div>
    </template>

    <el-form :model="form" label-width="120px" ref="formRef" :rules="rules">
      <!-- 入库仓库、供应商、经手人、业务日期放在一行 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="入库仓库*" prop="warehouse_name">
            <el-select v-model="form.warehouse_name" placeholder="请选择所属仓库" disabled>
              <el-option v-for="option in warehouseOptions" :key="option.value" :label="option.label"
                :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="供应商" prop="warehouse_name">
            <el-select v-model="form.supplier_name" placeholder="请选择供应商名称/编码" disabled>
              <el-option v-for="option in gysOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="经手人" prop="yclcg_ry">
            <el-select v-model="form.yclcg_ry" placeholder="请选择" disabled>
              <el-option v-for="option in jsrOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="业务日期" prop="yclcg_time">
            <el-date-picker v-model="form.yclcg_time" type="date" placeholder="请选择日期" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 表格部分 -->
      <el-table :data="cgxqData" style="width: 100%; margin-bottom: 20px;" border>
        <!-- 表格列定义 -->
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="物料编码" align="center" prop="wl_code" />
        <el-table-column label="物料名称" align="center" prop="wl_name" />
        <el-table-column label="数量" align="center" prop="yclcg_sl" />
        <el-table-column label="单位" align="center" prop="yclcg_dw" />
        <el-table-column label="单价（元）" align="center" prop="yclcg_dj" />
        <el-table-column label="小计（元）" align="center" prop="yclcg_xj" />
        <el-table-column label="备注" width="200" align="center" prop="bz" />

        <!-- 合计行 -->
        <template #append>
          <div style="display: flex; justify-content: flex-end; padding: 8px; background: #f5f7fa;">
            <span style="font-weight: bold; margin-right: 20px;">合计：</span>
            <span style="font-weight: bold;">{{ calculateTotal() }} 元</span>
          </div>
        </template>
      </el-table>

      <!-- 折扣率、折扣金额、附加金额、结算方式 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="折扣率%" prop="yclcg_zkl">
            <el-input v-model="form.yclcg_zkl" type="number" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="折扣金额（元）" prop="yclcg_zkje">
            <el-input v-model="form.yclcg_zkje" type="number" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="附加金额（元）" prop="yclcg_fjje">
            <el-input v-model="form.yclcg_fjje" type="number" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="结算方式" prop="yclcg_jsfs">
            <el-select v-model="form.yclcg_jsfs" placeholder="请选择" disabled>
              <el-option label="现金" value="cash" />
              <el-option label="信用卡" value="creditCard" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 单据备注 -->
      <el-form-item label="单据备注" prop="djbz">
        <el-input v-model="form.djbz" type="textarea" disabled />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="总计金额">
            <el-input v-model="form.yclcg_zje" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实收金额">
            <el-input v-model="form.yclcg_ssje" disabled />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit">通过</el-button>
        <el-button type="danger" @click="passSubmit">不通过</el-button>

      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
  setup() {
    const route = useRoute();
    const router = useRouter(); // 使用 useRouter
    const formRef = ref(null);
    const warehouseOptions = ref([]);
    const gysOptions = ref([]);
    const jsrOptions = ref([]);

    const form = reactive({
      yclcg_id: '',
      yclcg_code: '',
      //yclcg_ruck: '',
      //yclcg_gys: '',
      yclcg_ry: '',
      yclcg_time: '',
      yclcg_zkl: '',
      yclcg_zkje: '',
      yclcg_fjje: '',
      yclcg_jsfs: '',
      djbz: '',
      yclcg_zje: '',
      yclcg_ssje: '',
      yclcg_djzt: '',
      warehouse_name: '',
      supplier_name: '',
      dhcode: '',
      dhzt: ''
    });

    const cgxqData = ref([]);

    // 初始化数据
    onMounted(async () => {
      // 获取传递过来的 yclcg_code
      const yclcg_code = route.query.yclcg_code;

      // 根据 yclcg_code 查询数据主表
      const cgResponse = await axios.get(`api/Rm_yclcg/Getcg?code=${yclcg_code}`);
      const cg1 = cgResponse.data;

      // 根据 yclcg_code 查询数据子表
      const cgxqResponse = await axios.get(`api/Rm_yclcgxq/Getcgxq?code=${yclcg_code}`);
      const cgxq1 = cgxqResponse.data;

      // 将查询到的数据赋值给表单和表格
      Object.assign(form, cg1);

      // 确保 cgxq1 是一个数组
      if (Array.isArray(cgxq1)) {
        cgxqData.value = cgxq1;
      } else if (typeof cgxq1 === 'object' && cgxq1 !== null) {
        // 如果 cgxq1 是一个对象，将其转换为数组
        cgxqData.value = [cgxq1];
      } else {
        // 如果 cgxq1 是其他类型，初始化为空数组
        cgxqData.value = [];
      }

      // 确保数据在表格渲染之前赋值
      nextTick(() => {
        console.log('Table data updated:', cgxqData.value);
      });
    });





    // 计算合计金额
    const calculateTotal = () => {
      if (!Array.isArray(cgxqData.value) || cgxqData.value.length === 0) {
        return 0;
      }
      return cgxqData.value.reduce((total, item) => {
        const xj = parseFloat(item.yclcg_xj) || 0;
        return total + xj;
      }, 0);
    };


    // 计算折扣金额
    const calculateDiscount = () => {
      const totalAmount = calculateTotal();
      const discountRate = parseFloat(form.yclcg_zkl) || 0;

      if (isNaN(discountRate)) {
        form.yclcg_zkje = 0;
      } else {
        form.yclcg_zkje = (totalAmount - (totalAmount * (discountRate / 100))).toFixed(2);
      }

      // 更新总计金额
      form.yclcg_zje = (totalAmount - parseFloat(form.yclcg_zkje)).toFixed(2);
      // 更新实收金额
      calculateReceivedAmount();
    };

    // 计算实收金额
    const calculateReceivedAmount = () => {
      const totalAmount = parseFloat(form.yclcg_zje) || 0;
      const fj = parseFloat(form.yclcg_fjje) || 0;

      form.yclcg_ssje = (totalAmount + fj).toFixed(2);
    };



    // 提交审核
    const onSubmit = async () => {
      console.log('提交审核' + form.yclcg_code);
      const data = {
        yclcg_code: form.yclcg_code,
        yclcg_djzt: form.yclcg_djzt,
        dhzt: form.dhzt,
        dhcode: form.dhcode
      }
      console.log(data);
      const response = await axios.put('/api/Rm_yclcg/UpdateYclcg_zt?up=' + form.yclcg_code);
      console.log(response.data);
      if (response.data == 1) {
        console.log('审核成功');
         ElMessage.success('审核成功');
        router.push({ path: '/RawMaterialProcurement' });
      }
      else {
        console.log('审核失败');
      }
    };
    const passSubmit = async () => {
      console.log('不通过' + form.yclcg_code);
      const response = await axios.put('/api/Rm_yclcg/UpZtbtg?code=' + form.yclcg_code);
      console.log(response.data);
      if (response.data) {
        console.log('审核不通过');
         ElMessage.error('审核不通过');
        router.push({ path: '/RawMaterialProcurement' });
      }
      else {
        console.log('审核失败');
      }
    }
    // 取消
    const onCancel = () => {
      console.log('取消');
    };

    return {
      form,
      cgxqData,
      warehouseOptions,
      gysOptions,
      jsrOptions,
      calculateTotal,
      onSubmit,
      onCancel,
      passSubmit,
      calculateDiscount,
      calculateReceivedAmount
    };
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-center {
  text-align: center;
  flex: 1;
  /* 让标题占据剩余空间，使其居中 */
}

.document-number {
  font-size: 14px;
  color: #666;
}

.el-table {
  margin-bottom: 20px;
  /* 表格与下方内容隔开 */
}

.el-table--border {
  border: 1px solid #ebeef5;
}

.el-table--border th,
.el-table--border td {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}
</style>